import axios from 'axios'
import config from '../config/index'
import { ElMessage } from 'element-plus'
import router from '../router/router'
import storage from './storage'
const TOKEN_ERROR = 'Token认证失败'
const NETWOEK_ERROR = '网络请求异常'
//创建axios的实例对象 添加配置
const service = axios.create({
    baseURL:config.baseApi,
    timeout:8000
})
//请求拦截器

service.interceptors.request.use((req)=>{ 
    //一些公共的请求的机制
    const headers= req.headers
    const {token=''}=storage.getItem('userInfo') || {}
    if(!headers.Authorization) headers.Authorization = 'Bearer '+token
    return req
})
service.interceptors.response.use((res)=>{ 
    //一些公共的响应的机制
    const {code,data,msg}=res.data

    if(code===200){
        return data
    }else if(code===50001){
        ElMessage.error(TOKEN_ERROR)
        setTimeout(()=>{
            router.push('/login')
        },1500)
        return Promise.reject(TOKEN_ERROR)
    }else{
        ElMessage.error(NETWOEK_ERROR)
        return Promise.reject(NETWOEK_ERROR)
    }
})

//核心的request的函数
function request(options){
    options.method=options.method||'get'
    if(options.method.toLowerCase()==='get'){
        //统一 属性是data
        options.params=options.data
    }
    let ismock = config.mock
    if(typeof options.mock !=='undefined'){
        ismock=options.mock

    }
    //如果是生产环境
    if(config.env ==='prod'){
        service.defaults.baseURL=config.baseApi
    }else{
        service.defaults.baseURL= ismock? config.mockApi:config.baseApi
    }
    return service(options)
}
['get','post','put','delete','patch'].forEach((item)=>{
    request[item]= (url,data,options)=>{
        return request({
            url,
            data,
            method:item,
            ...options
        })
    }
})
export default request